export default (authList: AuthArray<string> = []) => {
  const routerContext = require.context('../pages', true, /\.vue$/)

  const routes: RoutesMap[] = []
  const pathMap: PathMap = {}
  const routerKeys = routerContext.keys()

  for (let router of routerKeys) {
    const path = router.replace(/^\./, '').replace(/.vue$/, '')
    const ctrl = routerContext(router)
    const routerComp = ctrl.default || ctrl
    const routerName: string =
      routerComp.extendOptions.name || routerComp.name || ''

    if (routerName === 'notFound' && !pathMap[path]) {
      const notFoundRoute = {
        name: routerName,
        path: '*',
        component: routerComp
      }
      pathMap[path] = notFoundRoute
      routes.push(notFoundRoute)
      continue
    }
    if (!authList.includes(routerName)) continue

    let obj: RoutesMap | undefined = {
      path: path,
      name: routerName,
      //  () => import(`@/pages${path}`)
      component: routerComp
    }

    const meta: MetaType = routerComp.extendOptions.meta
    if (meta && Object.keys(meta).length > 0) {
      obj.meta = meta
    }
    const hidden = routerComp.extendOptions.hidden
    hidden && (obj.hidden = hidden)

    const lastIndex = path.lastIndexOf('index')

    const lastIndexPosition = path.length - lastIndex
    const isLastFix = lastIndexPosition === 5
    const isHeadFix = lastIndex === 1

    if (isLastFix && !isHeadFix) {
      obj.path = path.replace(/\/index$/, '')
    } else if (!isLastFix && isHeadFix) {
      obj.path = path.replace(/^\/index\//, '/')
    } else if (isLastFix && isHeadFix) {
      obj.path = path.replace(/^\/index/, '/')
    }

    const indexRouteGroup = path.split('/')
    const routeLast = indexRouteGroup[indexRouteGroup.length - 1]
    const routeLastIndex = path.indexOf(routeLast) - 1
    const prefixIndexRoute = path.slice(0, routeLastIndex)
    const routeActGroup = routeLast.split(/_/g)
    const routeActGroupLen = routeActGroup.length

    if (routeActGroupLen > 2) throw new Error(`暂不支持多级动态路由`)
    else if (routeActGroupLen === 2) {
      obj.path = `${prefixIndexRoute}/${routeActGroup[0]}/:${routeActGroup[1]}`
    }

    const _path: string = obj.path
    if (!pathMap[_path]) {
      pathMap[_path] = obj
      routes.push(obj)
    } else {
      obj = void 0
      throw new Error(`the path "${_path}" has already declared.`)
    }
  }
  console.log(routes)
  return routes
}
